package cn.com.open.itembank.service.impl;

import cn.com.open.itembank.common.GlobalConst;
import cn.com.open.itembank.common.enums.SysState;
import cn.com.open.itembank.common.enums.YesOrNo;
import cn.com.open.itembank.dto.Category;
import cn.com.open.itembank.dto.ReturnModel;
import cn.com.open.itembank.entity.QuestionCategory;
import cn.com.open.itembank.mapper.QuestionCategoryMapper;
import cn.com.open.itembank.service.QuestionCategoryService;
import cn.com.open.itembank.utils.DateUtil;
import cn.com.open.itembank.utils.RegxUtil;
import cn.com.open.itembank.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by lucky on 2017/7/31.
 */
@Service("questionCategoryService")
public class QuestionCategoryServiceImpl implements QuestionCategoryService {
    
    @Autowired
    private QuestionCategoryMapper mapper;

    //region 获取试题应用类别信息

    /**
     * 根据试题应用类别id获取可用试题应用类别信息.
     *
     * @param id 试题应用类别id
     * @return 可用题库信息
     */
    @Override
    public QuestionCategory getQuestionCategoryInfo(String id) {
        if (StringUtil.isEmpty(id)) {
            return null;
        }
        RegxUtil regxUtil = new RegxUtil();
        if (!regxUtil.regx(id)) {
            QuestionCategory questionCategory = mapper.isExistQuestionCategoryForInsert(id);
            return mapper.getEnabledById(questionCategory.getQuestionCategoryID());
        }
        return mapper.getEnabledById(id);
    }
    //endregion

    //region 各类存在判断

    /**
     * 判断是新增否存在重名.
     *
     * @param name 试题应用类别名称
     * @return false，不存在；true，存在；
     */
    private boolean isExistQuestionCategoryForInsert(String name) {
        QuestionCategory model = mapper.isExistQuestionCategoryForInsert(name);
        return (model != null);
    }

    /**
     * 判断修改是否存在重名.
     *
     * @param id   试题应用类别id
     * @param name 试题应用类别名称
     * @return false，不存在；true，存在；
     */
    private boolean isExistQuestionCategoryForUpdate(String id, String name) {
        QuestionCategory model = mapper.isExistQuestionCategoryForUpdate(id, name);
        return (model != null);
    }
    //endregion

    //region 获取各类列表

    /**
     * 获取试题应用类别名称信息
     *
     * @param name    试题应用类别名称
     * @param enabled true 表示只获取可用应用类别
     * @return the list
     */
    @Override
    public List<QuestionCategory> getList(String name, Boolean enabled) {
        return mapper.getList(name, enabled);
    }

    /**
     * 根据试题应用类别名称串获取试题应用类别id串.
     *
     * @param names 试题应用类别名称串，逗号分割
     * @return the list
     */
    @Override
    public String getIdsFromNames(String names) {
        List<String> list = new ArrayList<>();

        for (String name : names.split(",")) {
            if (mapper.getEnabledByName(name) != null) {
                list.add(mapper.getEnabledByName(name).getQuestionCategoryID());
            }
        }

        return String.join(",", list);
    }
    //endregion

    //region 新增试题应用类别

    /**
     * 新增试题应用类别.
     *
     * @param model the model
     * @return the int
     */
    @Override
    public ReturnModel insert(Category model) {

        ReturnModel returnModel = new ReturnModel();

        if (model == null || StringUtil.isEmpty(model.getQuestionCategoryName())) {
            returnModel.setCode(GlobalConst.DATA_FORMAT_ERROR);
            return returnModel;
        }

        if (isExistQuestionCategoryForInsert(model.getQuestionCategoryName())) {
            returnModel.setCode(GlobalConst.DATA_EXIST);
            return returnModel;
        }

        String questionCategoryID = UUID.randomUUID().toString();
        QuestionCategory questionCategory = new QuestionCategory();
        questionCategory.setQuestionCategoryID(questionCategoryID);
        questionCategory.setStatus(YesOrNo.YES.getIndex());
        questionCategory.setQuestionCategoryName(model.getQuestionCategoryName());
        questionCategory.setCreateTime(DateUtil.getCurrentTimeToShowString());

        try {
            mapper.insert(questionCategory);
            returnModel.setCode(GlobalConst.SUCCESS);
            returnModel.setData(questionCategoryID);
            return returnModel;
        } catch (DataAccessException e) {
            returnModel.setCode(GlobalConst.DATA_BASE_ERROR);
            return returnModel;
        }
    }
    //endregion

    //region 修改试题应用类别

    /**
     * 修改试题应用类别.
     *
     * @param id                   试题应用类别id
     * @param questionCategoryName 试题应用类别名称
     * @return the int
     */
    @Override
    public int update(String id, String questionCategoryName) {
        //判断是否存在
        QuestionCategory category = mapper.getById(id);
        if (category == null) {
            return GlobalConst.COURSE_NOT_EXIST;
        }

        //修改时，名称不可以重复
        if (isExistQuestionCategoryForUpdate(id, questionCategoryName)) {
            return GlobalConst.DATA_EXIST;
        }

        try {
            mapper.update(id, questionCategoryName);
            return GlobalConst.SUCCESS;
        } catch (Exception e) {
            return GlobalConst.DATA_BASE_ERROR;
        }
    }

    /**
     * 更新试题应用类别状态.
     *
     * @param id 试题应用类别ID
     * @return the int
     */
    @Override
    public int changeStatus(String id) {
        //判断是否存在
        QuestionCategory category = mapper.getById(id);
        if (category == null) {
            return GlobalConst.COURSE_NOT_EXIST;
        }

        int oldStatus = category.getStatus();

        int newStatus = (oldStatus == SysState.STOP.getIndex()) ? SysState.START.getIndex() : SysState.STOP.getIndex();

        try {
            mapper.changeStatus(id, newStatus);
            return GlobalConst.SUCCESS;
        } catch (Exception e) {
            return GlobalConst.DATA_BASE_ERROR;
        }
    }
    //endregion

    //region 删除试题应用类别

    /**
     * 删除试题应用类别
     *
     * @param id 试题应用类别id
     * @return the int
     */
    @Override
    public int delete(String id) {

        //判断是否存在
        QuestionCategory category = mapper.getById(id);
        if (category == null) {
            return GlobalConst.ID_NOT_EXIST;
        }

        try {
            //如果课程存在自定义题型，试题，试卷，策略均无法删除(不判断章节)
            if (mapper.getQuestionCountByCategoryId(id) > 0) {
                return GlobalConst.DATA_EXIST;
            }
            //删除题库课程
            mapper.delete(id);

            return GlobalConst.SUCCESS;
        } catch (Exception e) {
            return GlobalConst.DATA_BASE_ERROR;
        }
    }
    //endregion
}
